<template>
  <div class="schedule-calendar-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>日程日历</span>
          <div class="header-controls">
            <el-button @click="toPrevMonth">上一月</el-button>
            <el-button @click="toCurrentMonth">本月</el-button>
            <el-button @click="toNextMonth">下一月</el-button>
            <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['oa:schedule-arrangement:create']">
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
          </div>
        </div>
      </template>
      <el-calendar v-model="calendarDate" :fullscreen="false">
        <template #date-cell="{ data }">
          <div :class="['custom-date-cell', { today: isToday(data.date), selected: isSelected(data.date) }]">
            <div class="day-number">{{ data.day.split('-')[2] }}</div>
            <div class="day-schedules">
              <template v-if="calendarData[formatDate(data.date)] && calendarData[formatDate(data.date)].length">
                <div
                  v-for="schedule in calendarData[formatDate(data.date)].slice(0,2)"
                  :key="schedule.id"
                  class="schedule-tag"
                  :title="schedule.scheduleContent"
                  @click.stop="openForm('update', schedule.id)"
                >
                  <dict-tag :type="DICT_TYPE.OA_PRIORITY_STATUS" :value="schedule.priorityLevel" />
                  <span class="schedule-content">{{ schedule.scheduleContent }}</span>
                  <el-tag v-if="Number(schedule.reminderSetting)" size="small" type="info">提醒</el-tag>
                </div>
                <div v-if="calendarData[formatDate(data.date)].length > 2" class="more-schedule">+{{ calendarData[formatDate(data.date)].length - 2 }}条</div>
              </template>
              <template v-else>
                <div class="no-schedule">-</div>
              </template>
            </div>
          </div>
        </template>
      </el-calendar>
    </el-card>
    <ScheduleArrangementForm ref="formRef" @success="loadCalendarData" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ScheduleArrangementApi, ScheduleArrangementVO } from '@/api/oa/schedulearrangement'
import ScheduleArrangementForm from './ScheduleArrangementForm.vue'
import { DICT_TYPE } from '@/utils/dict'

/** 日程日历页面（el-calendar重构版） */
defineOptions({ name: 'ScheduleCalendar' })

const calendarDate = ref(new Date())
const calendarData = ref<Record<string, ScheduleArrangementVO[]>>({})
const formRef = ref()
const selectedDate = ref(new Date())

const formatDate = (date: Date | string) => {
  const d = typeof date === 'string' ? new Date(date) : date
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}
const isToday = (date: Date | string) => {
  const d = typeof date === 'string' ? new Date(date) : date
  const now = new Date()
  return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()
}
const isSelected = (date: Date | string) => {
  const d = typeof date === 'string' ? new Date(date) : date
  return d.getFullYear() === selectedDate.value.getFullYear() && d.getMonth() === selectedDate.value.getMonth() && d.getDate() === selectedDate.value.getDate()
}

const loadCalendarData = async () => {
  // 取当前月首日和末日
  const year = calendarDate.value.getFullYear()
  const month = calendarDate.value.getMonth() + 1
  const firstDay = `${year}-${String(month).padStart(2, '0')}-01 00:00:00`
  const lastDayNum = new Date(year, month, 0).getDate()
  const lastDay = `${year}-${String(month).padStart(2, '0')}-${String(lastDayNum).padStart(2, '0')} 23:59:59`
  const params = {
    startTime: firstDay,
    endTime: lastDay,
    pageNo: 1,
    pageSize: 1000
  }
  const data = await ScheduleArrangementApi.getScheduleArrangementPage(params)
  const group: Record<string, ScheduleArrangementVO[]> = {}
  data.list.forEach((item: ScheduleArrangementVO) => {
    const date = formatDate(new Date(item.startTime))
    if (!group[date]) group[date] = []
    group[date].push(item)
  })
  calendarData.value = group
}

const openForm = (type: string, id?: number, defaultDate?: string) => {
  formRef.value.open(type, id, defaultDate)
}

const toPrevMonth = () => {
  const d = new Date(calendarDate.value)
  d.setMonth(d.getMonth() - 1)
  calendarDate.value = d
  loadCalendarData()
}
const toNextMonth = () => {
  const d = new Date(calendarDate.value)
  d.setMonth(d.getMonth() + 1)
  calendarDate.value = d
  loadCalendarData()
}
const toCurrentMonth = () => {
  calendarDate.value = new Date()
  loadCalendarData()
}

onMounted(() => {
  loadCalendarData()
})

// 监听月份切换，自动加载数据
watch(calendarDate, () => {
  loadCalendarData()
})
</script>

<style scoped>
.schedule-calendar-page {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-controls {
  display: flex;
  gap: 10px;
}
.el-calendar-table .el-calendar-day {
  padding: 0;
}
.custom-date-cell {
  min-height: 90px;
  padding: 6px 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}
.custom-date-cell.today {
  background: #e8f5e8;
  border: 2px solid #67c23a;
}
.custom-date-cell.selected {
  background: #e0f7fa;
  border: 2px solid #409eff;
}
::v-deep .el-calendar-table .is-selected {
  background: none !important;
  border: none !important;
}
.day-number {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
}
.day-schedules {
  margin-bottom: 4px;
}
.schedule-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.schedule-content {
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.more-schedule {
  font-size: 10px;
  color: #909399;
}
.no-schedule {
  color: #c0c4cc;
  font-size: 12px;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 2px;
  transition: background-color 0.2s;
}
.no-schedule:hover {
  background-color: #f5f7fa;
}
</style> 